package com.pansoft.openplanet.fragment;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.chat.event.RightTopMenuClickEvent;
import com.efounder.chat.http.JFCommonRequestManager;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.http.EFHttpRequest;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.utils.ResStringUtil;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.adapter.ChildWalletListAdapter;
import com.pansoft.openplanet.bean.Account;
import com.pansoft.openplanet.bean.AssetListBean;
import com.pansoft.openplanet.bean.WalletBean;
import com.pansoft.openplanet.constant.IPAssetsConstant;
import com.pansoft.openplanet.db.AccountDao;
import com.pansoft.openplanet.util.BalanceUtil;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.pansoft.openplanet.widget.WrapContentLinearLayoutManager;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.utilcode.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

public class PWRWalletListFragment extends BaseFragment implements View.OnClickListener {

    public static final String TAG = "PWRWalletListFragment";

    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private ChildWalletListAdapter childWalletListAdapter;
    private ArrayList<AssetListBean> assetList = new ArrayList<>();//当前关注的代币列表
    private int mode = IPAssetsConstant.CHAIN_ID_TURBOCHAIN;
    private String balance = "0";//钱包余额

    private LinearLayout llEmptyLayout;
    private Button tvCreateWallet;
    private Button tvRestoreWallet;
    private ImageView ivIcon;
    private TextView tvTextTitle;

    private User user;
    private List<WalletBean> walleatBeanList = new ArrayList<>();
    private AccountDao accountDao;
    private String pwr = "";
    private String address = "";
    private String originAddress;
    public PWRWalletListFragment() {
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.open_planet_fragment_wallet_list, container, false);

        initView(rootView);
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        EFHttpRequest.cancelRequest(TAG);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWalletChanged(Account account) {
        initData();
    }

    private void initView(View rootView) {
        recyclerView = rootView.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new WrapContentLinearLayoutManager(getActivity()));
        llEmptyLayout = (LinearLayout) rootView.findViewById(R.id.ll_empty_layout);
        tvCreateWallet = (Button) rootView.findViewById(R.id.tv_create_wallet);
        tvRestoreWallet = (Button) rootView.findViewById(R.id.tv_restore_wallet);
        ivIcon = (ImageView) rootView.findViewById(R.id.iv_icon);
        tvTextTitle = (TextView) rootView.findViewById(R.id.tv_text_title);
        tvRestoreWallet.setOnClickListener(this);
        tvCreateWallet.setOnClickListener(this);

        childWalletListAdapter = new ChildWalletListAdapter(getContext(), assetList, mode);
        recyclerView.setAdapter(childWalletListAdapter);
        initSwipeRefreshView(rootView);
    }

    private void initData(){
        getWallet();
        getBanlancefromServer();
        requestAttentionTokenData(originAddress);
    }
    /**
     * 初始化下拉刷新
     */
    private void initSwipeRefreshView(View rootView) {
        refreshLayout = rootView.findViewById(R.id.refreshLayout);
        refreshLayout.setEnableAutoLoadMore(false);//开启自动加载功能（非必须）
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                initData();
            }
        });
    }






    @Override
    public void onClick(View v) {
        int id = v.getId();

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void rightTopMenuClickEvent(RightTopMenuClickEvent event) {
        StubObject stubObject = (StubObject) event.getStubObject();
        String id = stubObject.getObject("id", "").toString();
//        if (id.equals("eth")) {
//            //StarAssetWalletPopup.showPopup(getActivity(), event.getView(), "eth");
////            StarAssetWalletPopup.showPopup(getActivity(), event.getView(), IPAssetsConstant.CHAIN_ID_ETH);
//
//        }

    }
    //从服务器获取余额
    private void getBanlancefromServer() {
        assetList.clear();
        //添加头部区域
        assetList.add(new AssetListBean.Builder().type(1).build());
        //添加第一条数据eth
        assetList.add(new AssetListBean.Builder().build());
        childWalletListAdapter.notifyDataSetChanged();
        if (walleatBeanList.size() == 0) {
            refreshLayout.finishRefresh();
            // dismissLoading();
            //ToastUtil.showToast(getApplicationContext(), "请先添加新账户或者导入账户");
        } else {
            HashMap<String, String> map = new HashMap<>();
            map.put("ethAddress", walleatBeanList.get(0).getAddress());
            TCRequestUtil.postCommonRequest(TAG, "eth/ethGetBalance", map, new TCRequestUtil.TCRequestCallback() {
                @Override
                public void onSuccess(String response) {
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(response);
                        if (jsonObject != null && jsonObject.getString("result").equals("success")) {
                            String balance = jsonObject.getString("balance");
                            balance = BalanceUtil.balanceConvert(balance);
                            walleatBeanList.get(0).setBalance(balance);
                            if (balance.equals("0")) {
                                pwr = balance;
                            } else {
                                pwr = BalanceUtil.formatPrice(Double.valueOf(balance), true, 8);
                            }
                            childWalletListAdapter.setData(pwr);

//                            double cnyAmount = TCMathUtil.mul(Double.valueOf(balance), 100);
//                            tvCnyAmount.setText("￥ "+BalanceUtil.formatPrice(cnyAmount, true, 2));

                            refreshLayout.finishRefresh();
                            //dismissLoading();
                        }
                    } catch (Exception e) {
                        refreshLayout.finishRefresh();
                        e.printStackTrace();
                        // dismissLoading();
                    }
                }

                @Override
                public void onFail(String error) {
                    refreshLayout.finishRefresh();
                    if(!isAdded()){
                        return;
                    }
                    //dismissLoading();
                    ToastUtils.setBgColor(getResources().getColor(R.color.black));
                    ToastUtils.setMsgColor(getResources().getColor(R.color.op_text_white_color));
                    ToastUtils.showShort(ResStringUtil.getString(R.string.common_text_http_request_data_fail));
                }
            });
        }
    }

    //获取本地钱包地址
    private List<WalletBean> getWallet() {

        Account mainAccount = new AccountDao(getActivity()).getMainAccount();
        if (mainAccount == null) {
            mainAccount = accountDao.getAccount(EnvironmentVariable.getProperty("tc_ethAddress"));
            if (mainAccount != null) {
                mainAccount.setMaster(true);
                mainAccount.setEnable(true);
                mainAccount.setImUserId(EnvironmentVariable.getProperty(CHAT_USER_ID));
                accountDao.insertOrReplace(mainAccount);
            } else {
                return walleatBeanList;
            }
        }
        WalletBean walletBean = new WalletBean();
        walletBean.setAddress(mainAccount.getAddress());
        walletBean.setFile(new File(mainAccount.getFileName()));
        walletBean.setFilePath(mainAccount.getFileName());
        walletBean.setAccountName(mainAccount.getAcccountName());
        walletBean.setAvatar(mainAccount.getAccountAvatar());
        walleatBeanList.add(walletBean);
        address = walleatBeanList.get(0).getAddress();
        originAddress = address;
        if (address.length() > 20) {
            address = address.replace(address.substring(6, address.length() - 4), "****");
            return walleatBeanList;
        } else {
            return walleatBeanList;
        }

    }

    /**
     * 请求关闭的代币数据
     *
     * @param address
     */
    private void requestAttentionTokenData(String address) {
        assetList.clear();
        //添加头部区域
        assetList.add(new AssetListBean.Builder().type(1).build());
        //添加第一条数据eth
        assetList.add(new AssetListBean.Builder().build());
        childWalletListAdapter.notifyDataSetChanged();
        HashMap<String, String> params = new HashMap<>();
        params.put("chainID", IPAssetsConstant.CHAIN_ID_TURBOCHAIN + "");//链编号，BTC传1，ETC传2
        params.put("userAddress", address);//用户钱包地址
        TCRequestUtil.getCommonRequest(TAG, "chain/getAllTokenBalanceByChainAndUserAddress",
                params, new TCRequestUtil.TCRequestCallback() {
                    @Override
                    public void onSuccess(String response) {
                        try {

                            JSONObject jsonObject = new JSONObject(response);
                            if (jsonObject.optString("result").equals("success")) {
                                balance = jsonObject.optString("AddressBalance", "0");
                                if ("0".equals(balance) || "".equals(balance)) {
                                    childWalletListAdapter.setData("0");
                                } else {
                                    balance = BalanceUtil.formatPrice(Double.valueOf(balance), true, 8);
                                    //将余额传给adapter，部分刷新界面，显示头部余额和第一项余额
                                    childWalletListAdapter.setData(balance);
                                }
                                //解析代币数据
                                JSONArray jsonArray = jsonObject.optJSONArray("AllTokenBalance");
                                if (jsonArray.length() > 0) {
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        JSONObject walletObject = jsonArray.getJSONObject(i);
                                        AssetListBean assetListBean = new AssetListBean.Builder()
                                                .address(walletObject.optString("tokenAddress"))
                                                .icon(walletObject.optString("tokenIcon"))
                                                .name(walletObject.optString("tokenName"))
                                                .secondName(walletObject.optString("tokenFullName"))
                                                .balance(walletObject.optString("balance"))
                                                .id(walletObject.optString("tokenID"))
                                                .blockChainID(walletObject.optString("blockChainID"))
                                                .tokenDecimals(walletObject.optInt("tokenDecimals"))
                                                .isSelected(walletObject.optBoolean("isSelected"))
                                                .build();
                                        assetList.add(assetListBean);
                                    }
                                }
                                childWalletListAdapter.notifyDataSetChanged();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            ToastUtils.showShort(ResStringUtil.getString(R.string.common_text_http_request_data_fail));
                        }
                        refreshLayout.finishRefresh();
                    }

                    @Override
                    public void onFail(String error) {
                        refreshLayout.finishRefresh();
                        ToastUtils.showShort(ResStringUtil.getString(R.string.common_text_http_request_data_fail));
                    }
                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        JFCommonRequestManager.getInstance().cannelOkHttpRequest(TAG);
    }
}
